local L = LibStub("AceLocale-3.0"):GetLocale("DoTimer_Options")
local SECTION_NAME = "DoTimer Anchors";

local function createGUI(name)
    local optionsTable = {
        { -- section 1
            { -- column 1
                {
                    type = "text",
                    text = name,
                },
            },
        },
        { -- section 2
            { -- column 1
                {
                    title = L["Locked"],
                    type = "checkButton",
                    tooltipText = L["If unchecked, you may change the location of the anchor by dragging any timer currently running on it."],
                    setting = "locked",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Display Names"],
                    type = "checkButton",
                    tooltipText = L["If checked, groups will have their name displayed at the head of the group."],
                    setting = "displayNames",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Display Icons"],
                    type = "checkButton",
                    tooltipText = L["If checked, groups will display a raid icon if applicable."],
                    setting = "displayIcons",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Move Name"],
                    type = "checkButton",
                    tooltipText = L["If checked, the group name will be moved to a more streamlined location."],
                    setting = "moveName",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Hide All"],
                    type = "checkButton",
                    tooltipText = L["If checked, this anchor (and all its timers) will be hidden from view."],
                    setting = "hideAll",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Group Direction"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets the direction new groups are added."],
                    values = {"up", "down", "left", "right"};
                    setting = "groupDirection",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Timer Direction"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets the direction new timers are added to a group."],
                    values = {"up", "down", "left", "right"};
                    setting = "timerDirection",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Overflow Direction"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets the direction overflow groups are added to a group."],
                    values = {"up", "down", "left", "right"};
                    setting = "overflowDirection",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Timer Sort"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets the manner in which timers in a group are sorted."],
                    values = {"Time Added (A)", "Time Added (D)", "Time Remaining (A)", "Time Remaining (D)", "Percent Remaining (A)", "Percent Remaining (D)", "Alphabetical (A)", "Alphabetical (D)"};
                    setting = "timerSortMethod",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Group Sort"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets the manner in which groups are sorted."],
                    values = {"Time Added (A)", "Time Added (D)", "Alphabetical (A)", "Alphabetical (D)"};
                    setting = "groupSortMethod",
                    hasToggle = name ~= "Default Anchor",
                }, 
                {
                    title = L["Justification"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets the justification of the timers and groups.  By default the timers/groups are aligned to the top or to the left, depending on situation.  This setting allows you to change that behavior."],
                    values = {"auto", "bottom", "right"};
                    setting = "timerJustification",
                    hasToggle = name ~= "Default Anchor",
                }, 
                {
                    title = L["Centering"],
                    type = "dropDownSelector",
                    tooltipText = L["Sets how the anchor is centered on the screen, if at all."],
                    values = {"none", "horizontal", "vertical"};
                    setting = "centering",
                    hasToggle = name ~= "Default Anchor",
                }, 
                {
                    title = L["Timer Setting"],
                    type = "dropDown",
                    tooltipText = L["Select the timer setting you want to apply to timers that don't have their own setting."],
                    func = function(self)
                        local setting = "defaultTimerSetting";
                        local info;
                        for timerName, settings in pairs(TimerLib:Get("timerSettings")) do
                            info = UIDropDownMenu_CreateInfo();
                            info.text = timerName;
                            info.checked = timerName == TimerLib:Get("anchorSettings", name, setting);
                            info.func = function() 
                                TimerLib:Set("anchorSettings", name, setting, timerName);
                                if self:GetParent().toggle then
                                    self:GetParent().toggle:SetChecked(true);
                                end
                                CloseDropDownMenus(); 
                            end
                            UIDropDownMenu_AddButton(info);
                        end
                    end,
                    setting = "defaultTimerSetting",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Name Text Color"],
                    type = "colorSelect",
                    tooltipText = L["Sets the color of the groups' name."],
                    setting = "nameTextColor",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
            },
            { -- column 2
                {
                    title = L["Group Spacing"],
                    type = "slider",
                    tooltipText = L["Sets the amount of space between groups."],
                    minValue = 0, 
                    maxValue = 20,
                    valueStep = 1,
                    setting = "groupSpacing",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Timer Spacing"],
                    type = "slider",
                    tooltipText = L["Sets the amount of space between timers."],
                    minValue = 0, 
                    maxValue = 10,
                    valueStep = 1,
                    setting = "timerSpacing",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Scale"],
                    type = "slider",
                    tooltipText = L["Sets the scale of the anchor."],
                    minValue = .5, 
                    maxValue = 2,
                    valueStep = .1,
                    setting = "scale",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Max Num Groups"],
                    type = "slider",
                    tooltipText = L["Sets the maximum number of displayable groups.  Zero means no restriction."],
                    minValue = 0, 
                    maxValue = 10,
                    valueStep = 1,
                    setting = "maxNumGroups",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = L["Overflow Point"],
                    type = "slider",
                    tooltipText = L["Sets the number of timers a group can have before it starts overflowing.  Overflow timers will be placed in a new group anchored relative to the original group."],
                    minValue = 0, 
                    maxValue = 20,
                    valueStep = 1,
                    setting = "overflowPoint",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["No Combat Alpha"],
                    type = "slider",
                    tooltipText = L["Sets the alpha of the anchor while out of combat."],
                    minValue = 0, 
                    maxValue = 1,
                    valueStep = .05,
                    setting = "standardAlpha",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Combat Alpha"],
                    type = "slider",
                    tooltipText = L["Sets the alpha of the anchor while in combat."],
                    minValue = 0, 
                    maxValue = 1,
                    valueStep = .05,
                    setting = "combatAlpha",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Mouseover Alpha"],
                    type = "slider",
                    tooltipText = L["Sets the alpha of the anchor while mousing over its groups."],
                    minValue = 0, 
                    maxValue = 1,
                    valueStep = .05,
                    setting = "mouseoverAlpha",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = L["Name Font Height"],
                    type = "slider",
                    tooltipText = L["Sets the height font for the group name."],
                    minValue = 5, 
                    maxValue = 20,
                    valueStep = 1,
                    setting = "nameFontHeight",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
            },
            { -- column 3
                {
                    title = L["Preview"],
                    type = "button",
                    tooltipText = L["Show a preview of timers on this anchor."],
                    func = function()
                        local offset = 0;
                        for i = 1, 2 do
                            local g = "Scary Mob " .. i;
                            for j = 1, 3 do
                                TimerLib:NewTimer({duration = 20, time = GetTime() - offset, name = "Cool Timer " .. j}, g, nil, nil, nil, nil, name);
                                offset = offset + .5;
                            end
                        end
                    end,
                },
                {
                    title = L["Reset Position"],
                    type = "button",
                    tooltipText = L["Reset the position of this anchor."],
                    func = function()
                        TimerLib:Set("anchorSettings", name, "positionX", nil);
                        TimerLib:Set("anchorSettings", name, "positionY", nil);
                    end,
                },
                "BREAK",
            },
        },
    };
    
    if not AsheylaLib:InSimpleMode() then
        local newButton;
        if name == "Default Anchor" then
            newButton = {
                title = L["Make New Anchor!"],
                type = "editBoxString",
                tooltipText = L["Type in the name of a new anchor to be customized."],
                scripts = {
                    OnEditFocusGained = function(self) self:SetText(""); self:HighlightText() end,
                    OnEnterPressed = function(self) 
            			local text = self:GetText();
            			if not TimerLib:Get("anchorSettings", text) then
                            TimerLib:Set("anchorSettings", text, {});
                            createGUI(text);
                        end
                        GUILib:ShowPanel(SECTION_NAME, text == "Default Anchor" and "main" or text);
                        self:ClearFocus();
            		end,
                },
            };
        elseif name ~= "DoTimer Anchor" and name ~= "Cooldowns Anchor" and name ~= "PlayerAuras Anchor" then
            newButton = {
                title = L["Delete"],
                type = "button",
                tooltipText = L["Deletes this anchor.  If a timer is added to an anchor that doesn't exist, the anchor will be recreated."],
                func = function() 
                    local frame = StaticPopup_Show("TIMERLIBANCHOR", name)
                    frame.data = name;
                end,
            };
        end
        optionsTable[1][1][1] = {optionsTable[1][1][1], newButton};
    end
    
    local defaultFunc = function()
        TimerLib:Set("anchorSettings", name, {});
        InterfaceOptionsFrame:Hide(); GUILib:ShowPanel(SECTION_NAME, name == "Default Anchor" and "main" or name);
    end
    
    local getFunc = function(...)
        local val = TimerLib:Get("anchorSettings", name, ...);
        local isReal = val ~= nil;
        if val == nil then
            val = TimerLib:Get("anchorSettings", "Default Anchor", ...);
        end
        return val, isReal;
    end
    
    local setFunc = function(...)
        TimerLib:Set("anchorSettings", name, ...);
    end
    
    local toggleTooltip = L["If this checkbutton is unchecked, the setting does not apply and a default value will be used instead.  The default value will be found by looking at Default Anchor."];

    GUILib:SetGUIPanel(SECTION_NAME, name == "Default Anchor" and "main" or name, TimerLib, optionsTable, {default = defaultFunc, get = getFunc, set = setFunc, toggleTooltip = toggleTooltip, allSimple = true});
end

StaticPopupDialogs["TIMERLIBANCHOR"] = {
    text = L["You are about to delete the anchor |cff00ff00%s|r.  Do you wish to proceed?"],
    button1 = L["Delete"],
    button2 = L["Cancel"],
    OnAccept = function(self, name) 
        TimerLib:Set("anchorSettings", name, nil);
        local cats = INTERFACEOPTIONS_ADDONCATEGORIES;
        for i = 1, #cats do
            if cats[i].name == name then
                table.remove(cats, i);
                break;
            end
        end
        for i = 1, #cats do
            if cats[i].name == SECTION_NAME then
                if not (cats[i + 1] and cats[i + 1].parent == cats[i].name) then
                    cats[i].hasChildren = false;
                    cats[i].collapsed = nil;
                end
                break;
            end
        end
        InterfaceOptionsFrame:Hide(); GUILib:ShowPanel(SECTION_NAME, "main");
    end,
    whileDead = 1,
    hideOnEscape = 1,
    timeout = 0,
}

local blacklist = {
    ["Default Anchor"] = true,
    ["DoTimer Mouseover"] = true,
    ["Notifications Anchor"] = true,
    ["DoTimer Anchor"] = true,
    ["Cooldowns Anchor"] = true,
    ["PlayerAuras Anchor"] = true,
};

local function createAnchorGUI()
    if AsheylaLib:InSimpleMode() then
        createGUI("Default Anchor");
    else
        createGUI("Default Anchor");
        createGUI("DoTimer Anchor");
        createGUI("DoTimer Mouseover");
        createGUI("Cooldowns Anchor");
        createGUI("PlayerAuras Anchor");
        createGUI("Notifications Anchor");
        for name in AsheylaLib:Alphabetize(TimerLib:Get("anchorSettings")) do
            if not blacklist[name] then
                createGUI(name);
            end
        end
    end
end
createAnchorGUI();
GUILib:AddGUICreationScript(createAnchorGUI);

local existing = {};
GUILib:AddProfileChangeScript(function()
    table.wipe(existing);
    local cats = INTERFACEOPTIONS_ADDONCATEGORIES;
    local parent;
    for i = #cats, 1, -1 do
        if cats[i].parent == SECTION_NAME then
            if TimerLib:Get("anchorSettings", cats[i].name) then
                table.insert(existing, cats[i].name);
                existing[cats[i].name] = true;
            else
                table.remove(cats, i);
            end
        elseif cats[i].name == SECTION_NAME then
            parent = cats[i];
        end
    end
    if #existing == 0 then
        parent.hasChildren = false;
        parent.collapsed = nil;
    end
    
    for name in AsheylaLib:Alphabetize(TimerLib:Get("anchorSettings")) do
        if name ~= "Default Anchor" and name ~= "DoTimer Mouseover" and name ~= "Notifications Anchor" and not existing[name] then
            createGUI(name);
        end
    end
end);
